package algotithm.interview.newcoder.test1;

import java.util.*;

/**
 * @author zhouyanxiang
 * @Date 2021-03-2021/3/4-20:48
 * @Title 查找字符串中出现频率topK的字符
 */
public class Solution {

    public static void main(String[] args) {
        String s = "abbcccddddeeeee";
        int k = 2;
        Solution solution = new Solution();
        List<Character> topK = solution.findTopK(s, k);
        for (int i = 0; i < topK.size(); i++) {
            System.out.print(topK.get(i) + " ");
        }
    }


    public List<Character> findTopK(String s,int k) {
        char[] c = s.toCharArray();
        HashMap<Character, Integer> map = new HashMap<>(26);
        for (int i = 0; i < c.length; i++) {
            map.put(c[i],map.getOrDefault(c[i],0) + 1);
        }
        List<Map.Entry<Character,Integer>> list = new ArrayList<>();
        for (Map.Entry entry : map.entrySet()) {
            list.add(entry);
        }
        Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
            @Override
            public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
                return o2.getValue() - o1.getValue();
            }
        });
        List<Character> res = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            res.add(list.get(i).getKey());
        }
        return res;
    }
}
